<template>
  <div class="common-layout">
    <el-container>
      <el-header style="padding:0;">
        <el-row style="height: 100%;">
          <el-col :span="16" style=" display: flex; align-items: center;">
            <el-input v-model="input" style="width: 240px;height: 36px; margin-right: 10px;" placeholder="搜索名称"
              clearable />
          </el-col>

          <el-col :span="8">

          </el-col>

        </el-row>
      </el-header>
      <el-main style="padding: 10px 0;">

        <el-table ref="tableRef" :data="filteredData" row-key="id" border table-layout="auto"
          @row-dblclick="rowDblClickFn">

          <el-table-column prop="id" label="ID" fixed="left" v-if="!isMobile" />

          <el-table-column prop="name" label="名称" />

          <el-table-column prop="type" label="文件类型">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon v-if="scope.row.type === 1" size="20" color="blue">
                  <Document />
                </el-icon>
                <el-icon v-else size="20" color="orange">
                  <FolderOpened />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.type === 0 ? '目录' : '文件' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="qrCode" label="二维码">
            <template #default="scope">
              <div style="display: flex; align-items: center; justify-content: center;">
                <!-- <img :src="scope.row.qrCode" alt="二维码" style="width: 50px;" @click="clickSaleFn(scope.row.qrCode)" /> -->

                <el-popover :width="350"
                  popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 0px;">
                  <template #reference>
                    <el-avatar :src="scope.row.qrCode" shape="square" />
                  </template>
                  <template #default>
                    <div class="demo-rich-conent" style="display: flex; justify-content: center;">
                      <el-avatar :size="350" :src="scope.row.qrCode" shape="square" />
                    </div>
                  </template>
                </el-popover>

              </div>
            </template>
          </el-table-column>

          <el-table-column prop="fileUrl" label="文件地址" show-overflow-tooltip min-width="300" v-if="!isMobile">
            <template #default="scope">
              <!-- <div style="display: flex; align-items: center">
                <span style="margin-left: 0px">{{ scope.row.fileUrl }}</span>
              </div> -->
              <el-link :href="scope.row.previewUrl" target="_blank">{{ scope.row.fileUrl }}</el-link>
            </template>
          </el-table-column>

        </el-table>


      </el-main>
    </el-container>

    <!-- <el-table :data="tableData1" style="width: 100%" row-key="id" border lazy :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="date" label="Date" />
      <el-table-column prop="name" label="Name" />
      <el-table-column prop="address" label="Address" />
    </el-table> -->
  </div>


</template>
<script lang="ts" setup>

import { Document, FolderOpened } from '@element-plus/icons-vue'

import { onBeforeUnmount, onMounted, ref, watch } from 'vue'

import { getListTreeById } from '~/Api/request'
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const isMobile = ref(window.innerWidth < 768);

const updateWindowSize = () => {
  isMobile.value = window.innerWidth < 768;

  // if (isMobile.value) {
  //   console.log('移动端');
  // } else {
  //   console.log('非移动端');
  // }
};
// // 使用watch来监听窗口大小变化（也可以使用其他方式）
watch(() => window.innerWidth, (newVal, oldVal) => {
  updateWindowSize();
},
  { immediate: false }
);
onMounted(() => {
  window.addEventListener("resize", updateWindowSize);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", updateWindowSize);
});

const route = useRoute()
const router = useRouter()

interface fileInter {
  id?: string
  name: string
  type: number
  previewUrl?: string
  fileUrl: string
  qrCode?: string
  status?: string
  children?: any[]
  Expand?: boolean
}

let qrCodeList = ref<fileInter[]>([])

//搜索框
let input = ref<string>('')

//表格
const tableRef = ref();

onMounted(() => {
  getListFn()
})

let pageInde = 1
let pageSize = 15
let searchKey = ''

function getListFn() {

  // getFileList(pageInde, pageSize, searchKey).then(res => {
  //   let { records } = res.data.data
  //   qrCodeList.value = records
  //   console.log(records, qrCodeList);
  // })

  getListTreeById(route.query.id as string).then(res => {
    qrCodeList.value = res.data.data
    console.log(qrCodeList);
  })

}

//筛选按name
// const filterNameData = computed(() => {
//   if (input.value.trim() === '') {
//     // 如果搜索文本为空，则返回原始数据
//     return [...qrCodeList.value];
//   }

//   return [...qrCodeList.value].filter(item =>
//     item.name.toLowerCase().includes(input.value.toLowerCase())
//   );

// });

//递归函数，用于筛选数据
function filterData(data: fileInter[], searchQuery: string): fileInter[] {
  if (!searchQuery) return data; // 如果没有搜索查询，返回原始数据

  return data.flatMap(item => {
    const matches = item.name.toLowerCase().includes(searchQuery.toLowerCase());
    const filteredChildren = item.children ? filterData(item.children, searchQuery) : [];

    // 如果当前项匹配或者其子项匹配，则包含当前项
    if (matches || filteredChildren.length > 0) {
      return [{
        ...item,
        children: filteredChildren, // 只有当有匹配的子项时才包含子项
      }];
    }
    return []; // 如果当前项及其子项都不匹配，则不包含当前项
  });
}

// 计算属性，用于根据输入值过滤数据
const filteredData = computed(() => {
  const searchQuery = input.value.trim();
  return filterData(qrCodeList.value, searchQuery);
});



const rowDblClickFn = (row: any, column: any, event: Event) => {
  // console.log(1111, row);
  // console.log(2222, column);
  // console.log(tableRef.value);

  if (row.type === 0 && row.children.length > 0) {
    row.Expand = !row.Expand
    tableRef.value!.toggleRowExpansion(row, row.Expand)
  } else if (row.type === 1) {
    // 假设 row.url 是跳转的目标网页地址
    const url = row.previewUrl; // 替换为实际的 URL 属性
    const target = '_blank'; // 表示在新窗口打开
    const options = 'noopener,noreferrer'; // 增加安全性

    window.open(url, target, options);
  }
}

</script>

<style scoped></style>